package com.example.demo.service;

import com.example.demo.mapper.OfficeDynamicSqlSupport;
import com.example.demo.mapper.OfficeMapper;
import com.example.demo.model.Office;
import com.example.demo.view.vo.OfficeInfoVo;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

@Service
public class OfficeService {

    private OfficeMapper officeMapper;

    private OfficeUserService officeUserService;

    @Autowired
    public void setOfficeUserService(OfficeUserService officeUserService){
        this.officeUserService = officeUserService;
    }

    @Autowired
    public void setOfficeMapper(OfficeMapper officeMapper){
        this.officeMapper = officeMapper;
    }

    public List<OfficeInfoVo> getRecentOffice(){
        SelectStatementProvider selectStatementProvider = select(OfficeMapper.selectList)
                .from(OfficeDynamicSqlSupport.office)
                .orderBy(OfficeDynamicSqlSupport.updateTime.descending())
                .limit(4)
                .build().render(RenderingStrategies.MYBATIS3);
        return getOfficeInfoVos(selectStatementProvider);
    }

    public List<OfficeInfoVo> getAllOffice(){
        SelectStatementProvider selectStatementProvider = select(OfficeMapper.selectList)
                .from(OfficeDynamicSqlSupport.office)
                .orderBy(OfficeDynamicSqlSupport.updateTime)
                .build().render(RenderingStrategies.MYBATIS3);
        return getOfficeInfoVos(selectStatementProvider);
    }

    private List<OfficeInfoVo> getOfficeInfoVos(SelectStatementProvider selectStatementProvider) {
        List<OfficeInfoVo> officeInfoVos = new ArrayList<>();
        for(Office office : officeMapper.selectMany(selectStatementProvider)){
            OfficeInfoVo officeInfoVo = new OfficeInfoVo();
            officeInfoVo.setOffice(office);
            officeInfoVo.setNum_Student(officeUserService.getNumOfOffice(office.getId()));
            officeInfoVos.add(officeInfoVo);
        }
        return officeInfoVos;
    }


    public boolean officeExist(String officeID){
        SelectStatementProvider selectStatementProvider = select(OfficeMapper.selectList)
                .from(OfficeDynamicSqlSupport.office)
                .where(OfficeDynamicSqlSupport.id,isEqualTo(officeID))
                .build().render(RenderingStrategies.MYBATIS3);
        return officeMapper.selectMany(selectStatementProvider).size() != 0;
    }
}
